<?php
/* FILE: process_create_item.php
 * DESCRIPTION: Process called when a user presses the add button in collection_item_list.php
 * POST DATA: rating, image_url, attribute data
 * GET DATA: cname (collection name)
 */ 
	 // Inialize session
	session_start();
	
	// Include database connection settings
	include('config.inc');
	include('includes/functions.php');
	
	$success = true;
	
	//Switch POST[0] to a numerical rating based on user's choice
	switch((string)$_POST[0])
	{
		case 'one': $rating = 1; break;
		case 'two': $rating = 2; break;
		case 'thr': $rating = 3; break;
		case 'four': $rating = 4; break;
		case 'five': $rating = 5; break;
		default: $rating = 0; break;
	}
	//Null value is okay - not required.
	$url = (string)$_POST[1];
	if($url == "")
	{
		$url = NULL;
	}
	//Check to see if bad post data for imageURL column
	else if(!isUrl($url))
	{
		header('Location: collection_item_list.php?colname='.$_GET['cname'].'&err=badurl');
		$success = false;
	}

	if($success)
	{	
		//Insert into the main item table
		$insert = "INSERT INTO item (item_rating, item_image_url, item_collection_name, item_user_id) VALUES (" 
				. mysql_real_escape_string($rating) 
				. ", \"" 
				. (urlencode($url)) 
				. "\", \"" 
				. mysql_real_escape_string($_GET['cname']) 
				. "\", \"" 
				. mysql_real_escape_string($_SESSION['user_name']) 
				. "\");";
		
		if(getUID($_GET['cname']) == $_SESSION['user_name'])
		{
			// Insert item into item table
			if(!mysql_query($insert))
			{
				die("An error occurred inserting into item table.");
			}
		}
		else
		{
			unset($_SESSION['user_name']);
			header('Location: index.php?err=denied');
			$success = false;
		}
		
		if($success)
		{
			// Grab the primary key of the item just added.
			$lastId = mysql_insert_id();
			
			// Get attribute types
			$getAttributeTypes = "SELECT attribute_type, attribute_name FROM attribute WHERE attribute_collection_name = '" 
								. mysql_real_escape_string($_GET['cname']) 
								. "' AND attribute_user_id = '" 
								. mysql_real_escape_string($_SESSION['user_name']) 
								. "' ORDER BY attribute_id;";
			
			//Insert into the collection's item table
			$query = "INSERT INTO " 
					. mysql_real_escape_string($_GET['cname']) 
					. " VALUES(" 
					. $lastId 
					. ", ";
			
			// Query to get attribute types for each column
			if(!$attributeTypeResult = mysql_query($getAttributeTypes))
			{
				removeItem($lastId);
				die("An problem occurred getting attribute column information");
			}
			
			for($i = 2; $i < count($_POST) && $success; $i++)
			{
				//Grab each columns attribute type.  We need to make sure we do this every iteration elsewise things get out of whack.
				$row = mysql_fetch_row($attributeTypeResult);
				
				/* If the input isn't null deal with input, 
				 * else output NULL to be entered into table.
				 */
				if((string) $_POST[$i] != "")
				{
					if(isVarChar($row[0]))
					{
						//This is a string so we need quotes
						$query = $query 
								. "\"" 
								. mysql_real_escape_string($_POST[$i]) 
								. "\"";
					}
					else if(isInteger($row[0]))
					{
						// Check is the input is in fact numeric
						if(isIntegerData($_POST[$i]))
						{
							//Not string don't need quotes
							$query = $query . mysql_real_escape_string($_POST[$i]);
						}
						// Throw error and clean up previously created stuff.
						else
						{	
							removeItem($lastId);
							$success = false;
							header('Location: collection_item_list.php?colname='.$_GET['cname'].'&err=badinput&clm='.$row[1]);
						}
					}
					else if(isReal($row[0]))
					{
						// Check is the input is in fact numeric
						if(isRealData($_POST[$i]))
						{
							//Not string don't need quotes
							$query = $query . mysql_real_escape_string($_POST[$i]);
						}
						// Throw error and clean up previously created stuff.
						else
						{
							removeItem($lastId);
							$success = false;
							header('Location: collection_item_list.php?colname='.$_GET['cname'].'&err=badinput&clm='.$row[1]);
						}
					}
				}
				else
				{
					$query = $query . "NULL";
				}
				
				// Add comma at the end of each attribute except the last one.
				if($i < count($_POST)-1)
				{
					$query = $query . ", ";
				}
			}
			
			if($success)
			{
				// Close out the query
				$query = $query . ");";
			
				if(getUID($_GET['cname']) == $_SESSION['user_name'])
				{
					// Add item to the collection specific table
					if(!mysql_query($query))
					{
						removeItem($lastId);
						die("An error has occurred adding the item.");
					}
					else
					{
						// Successful item creation.  Redirect back to it's collection item list.
						header('Location: collection_item_list.php?colname=' 
								. $_GET['cname'] );
					}
				}
				else
				{
					unset($_SESSION['user_name']);
					header('Location: index.php?err=denied');
				}
			}
		}
	}
?>